package com.weixin.gong.example.semaphore;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.Semaphore;

/**
 * 信号量控制并发数的例子
 * @author weixin.gong
 * @date 15-8-3 上午11:07
 */
public class SemaphoreTest {

    public static void main(String[] args) {
        final Resources resources = new Resources();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        resources.putAdd();
                        System.out.println(resources.toString());
                    }
                }
            }).start();
        }
    }


    //需要控制访问并发的类
    static class Resources {
        private final Semaphore max = new Semaphore(3);//最大并发数

        private Map<Long, Integer> map = Maps.newConcurrentMap();

        public void putAdd() {
            max.acquireUninterruptibly();
            try {
                long now = System.currentTimeMillis() / 100;
                if (map.containsKey(now)) {
                    map.put(now, map.get(now) + 1);
                }
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                max.release();
            }
        }

        @Override public String toString() {
            return "Resources{" +
                    "map=" + map +
                    '}';
        }
    }
}
